<template>
  <div class="approval-page">
    <!-- 只查看状态/操作记录 -->
    <div v-if="!isApprovalStep" class="view-step">
      <div class="approval-status">
        <el-icon size="48" color="#999">
          <WarningFilled />
        </el-icon>
        <div class="status-title">审批中</div>
        <div class="status-desc">
          稍等，入住申请正在审批中，若该申请单长时间未处理，请联系相关审批人员！
        </div>
      </div>

      <!-- 操作记录：按「任务名+右侧时间」「人名(状态)」布局 -->
      <div class="record-section mt-4">
        <div class="record-title">操作记录</div>
        <div class="record-list">
          <!-- 单个操作记录项 -->
          <div v-for="(item, idx) in operationRecords" :key="idx" class="record-item">
            <!-- 第一行：任务名称（左） + 结束时间/正在处理（右） -->
            <div class="record-header">
              <span class="task-name">{{ item.action }}</span>
              <span class="end-time">{{ item.endTimeText }}</span>
            </div>
            <!-- 第二行：操作人（右括号内状态与结束时间关联） -->
            <div class="record-operator">{{ item.operator }}（{{ item.statusText }}）</div>
          </div>
          <!-- 空数据提示 -->
          <div v-if="operationRecords.length === 0" class="empty-record">暂无操作记录</div>
        </div>
      </div>

      <div class="user-footer mt-4">
        <el-button @click="handleReturn" type="default" size="mini">返回</el-button>
      </div>
    </div>

    <!-- 可审批页面 -->
    <div v-else class="approval-step">
      <el-row :gutter="20">
        <!-- 左侧信息区：完全保留原代码 -->
        <el-col :span="16">
          <!-- 基本信息 -->
          <div class="section basic-info">
            <div class="section-header">
              <span class="section-number">1</span> 基本信息
            </div>
            <el-descriptions :column="1" label-align="left"
              :label-style="{ width: '120px', fontWeight: 600, color: '#333' }"
              :content-style="{ color: '#666', wordBreak: 'break-all' }" class="mt-2">
              <el-descriptions-item label="老人姓名">{{ basicInfo.name }}</el-descriptions-item>
              <el-descriptions-item label="老人身份证号">{{ basicInfo.idCard }}</el-descriptions-item>
              <el-descriptions-item label="性别">{{ basicInfo.gender }}</el-descriptions-item>
              <el-descriptions-item label="出生日期">{{ basicInfo.birth }}</el-descriptions-item>
              <el-descriptions-item label="年龄">{{ basicInfo.age }}</el-descriptions-item>
              <el-descriptions-item label="详细住址">{{ basicInfo.address }}</el-descriptions-item>
            </el-descriptions>
          </div>

          <!-- 健康状况 -->
          <div class="section health-status">
            <div class="section-header">
              <span class="section-number">2</span> 健康状况
            </div>
            <div class="sub-section">
              <div class="sub-title">疾病和用药情况</div>
              <div class="disease-diagnosis mt-2">
                <span class="field-label">疾病诊断：</span>
                <el-tag v-for="(disease, idx) in healthInfo.diseases" :key="idx" type="info">{{ disease }}</el-tag>
              </div>
              <div class="mt-4">
                <span class="field-label">用药情况：</span>
                <el-table :data="healthInfo.medicines" border style="width: 100%" size="mini">
                  <el-table-column label="药物名称" prop="name" />
                  <el-table-column label="服药方法" prop="method" />
                  <el-table-column label="用药剂量" prop="dosage" />
                </el-table>
              </div>
            </div>

            <div class="sub-section mt-4">
              <div class="sub-title">近30天内风险事件</div>
              <el-row :gutter="20" class="mt-2">
                <el-col :span="12">
                  <div class="risk-item">
                    <span class="event-key">跌倒：</span>
                    <el-tag :type="getRiskTagType(healthInfo.riskEvents.跌倒)">{{ healthInfo.riskEvents.跌倒 }}</el-tag>
                  </div>
                  <div class="risk-item mt-2">
                    <span class="event-key">噎食：</span>
                    <el-tag :type="getRiskTagType(healthInfo.riskEvents.噎食)">{{ healthInfo.riskEvents.噎食 }}</el-tag>
                  </div>
                  <div class="risk-item mt-2">
                    <span class="event-key">昏迷：</span>
                    <el-tag :type="getRiskTagType(healthInfo.riskEvents.昏迷)">{{ healthInfo.riskEvents.昏迷 }}</el-tag>
                  </div>
                </el-col>
                <el-col :span="12">
                  <div class="risk-item">
                    <span class="event-key">走失：</span>
                    <el-tag :type="getRiskTagType(healthInfo.riskEvents.走失)">{{ healthInfo.riskEvents.走失 }}</el-tag>
                  </div>
                  <div class="risk-item mt-2">
                    <span class="event-key">自杀：</span>
                    <el-tag :type="getRiskTagType(healthInfo.riskEvents.自杀)">{{ healthInfo.riskEvents.自杀 }}</el-tag>
                  </div>
                </el-col>
              </el-row>
            </div>

            <div class="sub-section mt-4">
              <div class="sub-title">身体健康情况</div>
              <el-row :gutter="40" class="mt-2">
                <el-col :span="6">
                  <div class="health-item">
                    <span class="item-label">伤口情况：</span>
                    <el-tag v-for="(item, idx) in healthInfo.wound" :key="idx" type="info">{{ item }}</el-tag>
                  </div>
                </el-col>
                <el-col :span="6">
                  <div class="health-item">
                    <span class="item-label">特殊医疗照护情况：</span>
                    <el-tag v-for="(item, idx) in healthInfo.medicalCare" :key="idx" type="info">{{ item }}</el-tag>
                  </div>
                </el-col>
                <el-col :span="6">
                  <div class="health-item">
                    <span class="item-label">自理能力：</span>
                    <el-tag type="info">{{ healthInfo.selfCare }}</el-tag>
                  </div>
                </el-col>
                <el-col :span="6">
                  <div class="health-item">
                    <span class="item-label">痴呆前兆：</span>
                    <el-tag v-for="(item, idx) in healthInfo.dementiaSign" :key="idx" type="info">{{ item }}</el-tag>
                  </div>
                </el-col>
                <el-col :span="24" class="health-item">
                  <span class="item-label">其他：</span>
                  {{ healthInfo.other }}
                </el-col>
              </el-row>
            </div>

            <div class="sub-section mt-4">
              <div class="sub-title">近期体检报告</div>
              <div class="mt-2">
                <span class="event-key">体检报告：</span>
                <span class="report-name">{{ healthInfo.medicalReport.name }}</span>
                <a :href="healthInfo.medicalReport.url" target="_blank" class="view-link ml-2">查看</a>
              </div>
            </div>
          </div>

          <!-- 能力评估 -->
          <div class="section ability-status">
            <div class="section-header">
              <span class="section-number">3</span> 能力状况
            </div>
            <div class="sub-section">
              <div class="sub-title">能力评估结果</div>
              <el-row :gutter="80" class="mt-2">
                <el-col :span="8">
                  <div class="ability-item">
                    <span class="item-label">自理能力得分（分）：</span>
                    {{ abilityInfo.selfCareScore }}
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="ability-item">
                    <span class="item-label">精神状态得分（分）：</span>
                    {{ abilityInfo.mentalScore }}
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="ability-item">
                    <span class="item-label">感知觉与社会参与得分（分）：</span>
                    {{ abilityInfo.socialScore }}
                  </div>
                </el-col>
              </el-row>
              <el-row class="mt-2" :gutter="40">
                <el-col :span="8">
                  <div class="ability-item">
                    <span class="item-label">评估总分（分）：</span>
                    {{ abilityInfo.totalScore }}
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="ability-item">
                    <span class="item-label">能力初步等级：</span>
                    {{ abilityInfo.initialLevel }}
                  </div>
                </el-col>
              </el-row>
              <div class="mt-4">
                <span class="event-key">能力等级变更依据：</span>
                <el-tag v-for="(basis, idx) in abilityInfo.changeBasis" :key="idx" type="info"
                  style="margin-right: 8px;">{{ basis }}</el-tag>
                <div class="mt-2 other-basis">{{ abilityInfo.otherBasis || '无' }}</div>
              </div>
              <div class="mt-2">
                <span class="event-key">能力最终等级：</span>
                <el-tag :type="getLevelTagType(abilityInfo.finalLevel)">
                  {{ abilityInfo.finalLevel }}
                </el-tag>
              </div>
            </div>
          </div>
        </el-col>

        <!-- 右侧审批区 -->
        <el-col :span="8">
          <div class="section approval-section">
            <div class="section-header">审批结果</div>
            <el-form ref="approvalFormRef" :model="approvalForm" :rules="approvalRules" label-width="100px"
              class="mt-2">
              <el-form-item label="*审批结果" prop="result">
                <el-radio-group v-model="approvalForm.result">
                  <el-radio label="审批通过" />
                  <el-radio label="审批拒绝" />
                  <el-radio label="驳回" />
                </el-radio-group>
              </el-form-item>
              <el-form-item label="*审批意见" prop="opinion">
                <el-input type="textarea" v-model="approvalForm.opinion" placeholder="请输入审批意见" maxlength="200"
                  show-word-limit />
              </el-form-item>
            </el-form>

            <!-- 右侧操作记录：同样按「任务名+右侧时间」「人名(状态)」布局 -->
            <div class="section-header mt-4">操作记录</div>
            <div class="record-list mt-2">
              <div v-for="(item, idx) in operationRecords" :key="idx" class="record-item">
                <div class="record-header">
                  <span class="task-name">{{ item.action }}</span>
                  <span class="end-time">{{ item.endTimeText }}</span>
                </div>
                <div class="record-operator">{{ item.operator }}（{{ item.statusText }}）</div>
              </div>
              <div v-if="operationRecords.length === 0" class="empty-record">暂无操作记录</div>
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 底部按钮 -->
      <el-row class="bottom-buttons">
        <el-col :span="24" class="text-center">
          <el-button @click="handleReturn">返回</el-button>
          <el-button type="primary" @click="handleSubmit" class="ml-4">提交</el-button>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { WarningFilled } from '@element-plus/icons-vue'
import { useRoute } from 'vue-router'
import { submitApproval, getElderInfo, getApprovalRecord } from '@/api/checkInApply/checkInApply'

const route = useRoute()
const taskId = ref(route.query.taskId || '')
const taskName = ref(route.query.taskName || '')
const processInstanceId = ref(route.query.processInstanceId || '')

// 是否显示审批表单
const isApprovalStep = ref(true)

// 初始化响应式数据（完全保留原代码）
const basicInfo = reactive({
  name: '',
  idCard: '',
  gender: '',
  birth: '',
  address: '',
  age: ''
})

const healthInfo = reactive({
  diseases: [],
  medicines: [],
  riskEvents: { 跌倒: '', 走失: '', 噎食: '', 自杀: '', 昏迷: '' },
  wound: [],
  medicalCare: [],
  selfCare: '',
  dementiaSign: [],
  other: '',
  medicalReport: { name: '', url: '#' }
})

const abilityInfo = reactive({
  selfCareScore: 0,
  mentalScore: 0,
  socialScore: 0,
  totalScore: 0,
  initialLevel: '',
  changeBasis: [],
  otherBasis: '',
  finalLevel: ''
})

// 操作记录：reactive数组（按你的规则存储字段）
const operationRecords = reactive([])
// 静态 fallback 记录（接口失败时用）
const staticRecords = [
  {
    action: '发起申请-申请入住',
    endTime: '2048-10-15 09:00:00', // 有结束时间
    operator: '顾廷烨',
    endTimeText: '2048-10-15 09:00:00',
    statusText: '已完成'
  },
  {
    action: '处理-入住评估',
    endTime: '2048-10-15 09:30:00', // 有结束时间
    operator: '盛明兰',
    endTimeText: '2048-10-15 09:30:00',
    statusText: '已完成'
  },
  {
    action: '审批-申请审批',
    endTime: null, // 无结束时间
    operator: '盛明兰',
    endTimeText: '正在处理',
    statusText: '正在处理'
  }
]

// 审批表单（完全保留原代码）
const approvalForm = reactive({ result: '', opinion: '' })
const approvalFormRef = ref(null)
const approvalRules = {
  result: [{ required: true, message: '请选择审批结果', trigger: 'change' }],
  opinion: [{ required: true, message: '请输入审批意见', trigger: 'blur' }]
}

// 核心：处理结束时间和状态的逻辑（严格按你的规则）
const formatRecordData = (apiItem) => {
  const taskInfo = apiItem.taskInfo
  const userInfo = apiItem.userInfo

  // 规则1：有endTime显示格式化时间，无则显示“正在处理”
  const hasEndTime = !!taskInfo.endTime
  const endTimeText = hasEndTime 
    ? new Date(taskInfo.endTime).toLocaleString('zh-CN', {
        year: 'numeric', month: '2-digit', day: '2-digit',
        hour: '2-digit', minute: '2-digit', second: '2-digit',
        hour12: false
      }).replace(/\//g, '-')
    : '正在处理'

  // 规则2：有endTime状态“已完成”，无则“正在处理”
  const statusText = hasEndTime ? '已完成' : '正在处理'

  return {
    action: taskInfo.name || '未知操作', // 任务名称
    endTime: taskInfo.endTime, // 原始结束时间（用于后续判断）
    operator: userInfo.userName || '未知用户', // 操作人
    endTimeText: endTimeText, // 格式化后的时间文本
    statusText: statusText // 最终显示的状态
  }
}

// 风险事件颜色（保留原代码）
const getRiskTagType = (event) => {
  if (event.includes('3次以上')) return 'danger'
  if (event.includes('两次') || event.includes('2次')) return 'warning'
  return 'info'
}

// 能力等级颜色（保留原代码）
const getLevelTagType = (level) => {
  if (level.includes('中重度') || level.includes('重度')) return 'danger'
  if (level.includes('中度')) return 'warning'
  return 'info'
}

// 返回（保留原代码）
const handleReturn = () => { ElMessage.info('已返回') }

// 提交审批：追加操作记录（符合你的布局规则）
const handleSubmit = () => {
  approvalFormRef.value.validate(async (valid) => {
    if (!valid) return
    let shenHE = 1
    if (approvalForm.result === '审批拒绝') shenHE = 2
    if (approvalForm.result === '驳回') shenHE = 3
    const param = {
      businessId: processInstanceId.value,
      message: approvalForm.opinion,
      taskId: taskId.value,
      shenHE
    };
    submitApproval(param)
      .then(() => {
        ElMessage.success("审批提交成功！");
        // 追加最新审批记录（按你的规则）
        const newRecord = {
          action: `审批-${approvalForm.result}`,
          endTime: new Date().toISOString(), // 提交即有结束时间
          operator: '当前用户', // 实际项目替换为登录用户
          endTimeText: new Date().toLocaleString('zh-CN', {
            year: 'numeric', month: '2-digit', day: '2-digit',
            hour: '2-digit', minute: '2-digit', second: '2-digit',
            hour12: false
          }).replace(/\//g, '-'),
          statusText: '已完成' // 有结束时间→已完成
        }
        operationRecords.unshift(newRecord) // 追加到顶部
      })
      .catch((err) => {
        ElMessage.error("审批提交失败！");
        console.error(err);
      });
  })
}

// 页面加载：获取数据（只修改操作记录相关逻辑）
onMounted(() => {
  // 加载老人信息（保留原代码）
  if (taskName.value === '副院长审批-处理') {
    isApprovalStep.value = true
    getElderInfo({ bussinessId: route.query.processInstanceId })
      .then((response) => {
        const data = response.data
        console.log('后端返回数据:', data)

        // 1. 填充基本信息（保留原代码）
        basicInfo.name = data.name || ''
        basicInfo.idCard = data.idCard || ''
        basicInfo.gender = data.gender === '1' ? '男' : data.gender === '2' ? '女' : '未知'
        basicInfo.age = data.age || ''
        if (data.idCard && data.idCard.length >= 18) {
          const birthStr = data.idCard.substring(6, 14)
          if (birthStr.length === 8) {
            const year = birthStr.substring(0, 4)
            const month = birthStr.substring(4, 6)
            const day = birthStr.substring(6, 8)
            basicInfo.birth = `${year}-${month}-${day}`
          }
        }
        basicInfo.address = data.address || ''

        // 2. 填充健康信息（保留原代码）
        const healthAssess = JSON.parse(data.healthAssessment || '{}')
        healthInfo.diseases = healthAssess.diseases || []
        healthInfo.medicines = healthAssess.medicines || []
        healthInfo.riskEvents = {
          跌倒: healthAssess.fall || '无',
          走失: healthAssess.lost || '无',
          噎食: healthAssess.choke || '无',
          自杀: healthAssess.suicide || '无',
          昏迷: healthAssess.coma || '无'
        }
        healthInfo.wound = healthAssess.wound || []
        healthInfo.medicalCare = healthAssess.medicalCare || []
        healthInfo.selfCare = healthAssess.selfCare || ''
        healthInfo.dementiaSign = healthAssess.dementiaSign || []
        healthInfo.other = healthAssess.other || '无'
        const reportList = healthAssess.medicalReport || []
        healthInfo.medicalReport = reportList.length > 0
          ? { name: reportList[0].name || '未知文件', url: reportList[0].url || '#' }
          : { name: '无体检报告', url: '#' }

        // 3. 填充能力评估信息（保留原代码）
        const assessReport = JSON.parse(data.assessmentReport || '{}')
        abilityInfo.selfCareScore = assessReport.selfCareScore || 0
        abilityInfo.mentalScore = assessReport.mentalScore || 0
        abilityInfo.socialScore = assessReport.socialScore || 0
        abilityInfo.totalScore = assessReport.totalScore || 0
        abilityInfo.initialLevel = assessReport.initialLevel || '未评估'
        abilityInfo.changeBasis = assessReport.changeBasis || []
        abilityInfo.otherBasis = assessReport.otherBasis || '无'
        abilityInfo.finalLevel = assessReport.finalLevel || '未评定'

        // 4. 加载操作记录（按你的规则处理）
        getApprovalRecord({ businessId: processInstanceId.value })
          .then(res => {
            if (res.code === 200 && res.data.length) {
              operationRecords.length = 0 // 清空原有数据
              // 按你的规则映射每一条记录
              res.data.forEach(apiItem => {
                operationRecords.push(formatRecordData(apiItem))
              })
            } else {
              // 接口无数据→用静态记录
              operationRecords.push(...staticRecords)
            }
          })
          .catch(err => {
            console.error('获取操作记录失败:', err)
            ElMessage.warning('操作记录加载失败，显示默认记录')
            operationRecords.push(...staticRecords)
          })

      })
      .catch((err) => {
        console.error('获取老人信息失败:', err)
        ElMessage.error('数据加载失败，请刷新重试')
        // 加载失败也显示静态记录
        operationRecords.push(...staticRecords)
      });
  } else {
    isApprovalStep.value = false
    // 非审批步骤加载操作记录
    getApprovalRecord({ businessId: processInstanceId.value })
      .then(res => {
        if (res.code === 200 && res.data.length) {
          operationRecords.length = 0
          res.data.forEach(apiItem => {
            operationRecords.push(formatRecordData(apiItem))
          })
        } else {
          operationRecords.push(...staticRecords)
        }
      })
      .catch(err => {
        console.error('获取操作记录失败:', err)
        operationRecords.push(...staticRecords)
      })
  }
})
</script>

<style scoped>
/* 保留所有原有样式，只新增操作记录相关样式 */
.approval-page {
  padding: 20px;
}

/* 原有样式全部保留... */
.section-header {
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 8px;
}

.section-number {
  font-weight: bold;
  margin-right: 6px;
  color: #409EFF;
}

.sub-section {
  margin-bottom: 12px;
}

.field-label,
.item-label,
.event-key {
  font-weight: 600;
  margin-right: 6px;
}

.view-step .approval-status {
  text-align: center;
  margin-top: 50px;
}

.status-title {
  font-size: 20px;
  font-weight: bold;
  margin-top: 12px;
}

.status-desc {
  font-size: 14px;
  color: #999;
  margin-top: 8px;
}

.bottom-buttons {
  margin-top: 20px;
}

.ability-item,
.health-item,
.risk-item {
  margin-bottom: 4px;
}

.other-basis {
  margin-top: 4px;
  color: #666;
}

.view-link {
  color: #409EFF;
  text-decoration: underline;
  cursor: pointer;
}

.view-step .record-section,
.view-step .user-footer {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.view-step .user-footer {
  margin-top: 20px;
}

.el-table--mini .el-table__cell {
  padding: 6px 12px;
}

.el-tag {
  margin-bottom: 4px;
  margin-right: 4px;
}

/* 新增：操作记录布局样式（核心） */
.record-list {
  width: 100%;
  border-radius: 4px;
  overflow: hidden;
}

.record-item {
  padding: 12px 16px;
  border-bottom: 1px solid #eee;
}

/* 第一行：任务名左，时间右 */
.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 6px;
}

.task-name {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.end-time {
  font-size: 12px;
  color: #999;
  white-space: nowrap;
}

/* 第二行：操作人及状态 */
.record-operator {
  font-size: 13px;
  color: #666;
}

/* 空数据提示 */
.empty-record {
  padding: 20px;
  text-align: center;
  color: #999;
  font-size: 14px;
}

/* 右侧审批区的操作记录适配 */
.approval-section .record-list {
  background-color: #f9f9f9;
}
</style>